import {
  chooseAddress,
  getSetting,
  openSetting,
  showModal,
  showToast,
  requestPayment
} from "../../utils/asyncWx.js";
const regeneratorRuntime = require("../../lib/runtime/runtime.js");
import { request } from "../../request/index";
Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    // 获取缓存中的addres
    const address = wx.getStorageSync("address");
    // 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];
    cart = cart.filter(v => v.checked);
    this.setData({ address });
    // 计算总价格和总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    });
    // 存储到data中
    this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    });
  },
  // 进行支付操作
  async goWxPay() {
    try {
      // // 先判断用户是否已经登录
      // const token = wx.getStorageSync("token");
      // if (!token) {
      //   wx.navigateTo({
      //     url: "/pages/auth/index"
      //   });
      //   return;
      // }
      // // 创建订单
      // // 准备请求头参数
      // const header = { Authorization: token };
      // // 准备请求体参数
      // const order_price = this.data.totlalPrice;
      // const consignee_addr = this.data.address.all;
      // const cart = this.data.cart;
      // let goods = [];
      // cart.forEach(v =>
      //   goods.push({
      //     goods_id: v.goods_id,
      //     goods_num: v.num,
      //     goods_price: v.goods_price
      //   })
      // );
      // const orederParams = { order_price, consignee_addr, goods };
      // const { order_num } = await request({
      //   url: "/my/orders/create",
      //   method: "POST",
      //   data: orederParams,
      //   header
      // });
      // // 发起请求 调用预支付接口
      // const { pay } = await request({
      //   url: "/my/orders/req_unifiedoerder",
      //   method: "POST",
      //   header,
      //   data: { order_num }
      // });
      // // 调用微信支付接口
      // await requestPayment(pay);
      // // 查看订单支付状态
      // const res = await request({
      //   url: "/my/orders/chkOrder",
      //   method: "POST",
      //   header,
      //   data: { order_num }
      // });
      await showToast({title:"支付成功！"})
      let newCart = wx.getStorageSync("cart")
      newCart = newCart.filter(v=>!v.checked)
      wx.getStorageSync("cart",newCart)
      // 跳转到订单页
      wx.navigateTo({
        url:"/pages/order/index"
      })
    } catch (error) {
      await showToast({title:"支付失败！"})
    }
  }
});
